# -*- coding:utf-8 -*-

"""
商品标题黑名单Controller
"""

from fastapi import APIRouter, Depends
from starlette.requests import Request
from sqlalchemy.ext.asyncio import AsyncSession

from config.get_db import get_db
from config.enums import BusinessType
from module_admin.annotation.log_annotation import Log
from module_admin.service.title_blacklist_service import TitleBlacklistService
from module_admin.service.login_service import LoginService
from module_admin.entity.vo.user_vo import CurrentUserModel
from utils.response_util import ResponseUtil
from utils.log_util import logger


titleBlacklistRouter = APIRouter(prefix="/system/title-blacklist", tags=["标题黑名单"])


@titleBlacklistRouter.get("/list")
async def get_list(
    keyword: str = None,
    match_type: str = None,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    获取标题黑名单列表（按用户隔离，管理员可查看所有用户的黑名单）
    """
    try:
        # ✅ 判断是否是管理员（role_id=1的超级管理员）
        role_id_list = [role.role_id for role in current_user.user.role]
        is_admin = 1 in role_id_list
        
        # ✅ 管理员可以查看所有用户的黑名单（不传user_id），普通用户只能查看自己的
        user_id = None if is_admin else current_user.user.user_id
        
        query_dict = {}
        if keyword:
            query_dict['keyword'] = keyword
        if match_type:
            query_dict['match_type'] = match_type
        
        blacklist = await TitleBlacklistService.get_list(db, query_dict, user_id=user_id)
        
        # ✅ 批量获取创建者用户名（避免N+1查询）
        from module_admin.entity.do.user_do import SysUser
        from sqlalchemy import select
        
        create_by_ids = list(set([item.create_by for item in blacklist if item.create_by]))
        user_name_map = {}
        if create_by_ids:
            user_query = select(SysUser.user_id, SysUser.user_name, SysUser.nick_name).where(
                SysUser.user_id.in_(create_by_ids),
                SysUser.del_flag == '0'
            )
            user_result = await db.execute(user_query)
            for row in user_result:
                user_id_val, user_name, nick_name = row
                # 优先使用昵称，如果没有则使用用户名
                display_name = nick_name if nick_name else user_name
                user_name_map[user_id_val] = display_name
        
        result = [
            {
                'id': item.id,
                'keyword': item.keyword,
                'match_type': item.match_type,
                'reason': item.reason,
                'remark': item.remark,
                'status': getattr(item, 'status', '0') or '0',  # ✅ 添加status字段，默认'0'
                'create_by': item.create_by,
                'create_by_name': user_name_map.get(item.create_by, f'用户ID: {item.create_by}'),  # ✅ 添加创建者用户名
                'create_time': item.create_time.isoformat() if item.create_time else None,
                'update_time': item.update_time.isoformat() if item.update_time else None
            }
            for item in blacklist
        ]
        
        return ResponseUtil.success(data=result, dict_content={'total': len(result)})
    except Exception as e:
        logger.error(f"获取标题黑名单列表失败: {e}")
        return ResponseUtil.failure(msg=str(e))


@titleBlacklistRouter.get("/{blacklist_id}")
async def get_by_id(
    blacklist_id: int,
    db: AsyncSession = Depends(get_db)
):
    """
    根据ID获取标题黑名单
    """
    try:
        blacklist = await TitleBlacklistService.get_by_id(db, blacklist_id)
        if not blacklist:
            return ResponseUtil.failure(msg="黑名单不存在")
        
        result = {
            'id': blacklist.id,
            'keyword': blacklist.keyword,
            'match_type': blacklist.match_type,
            'reason': blacklist.reason,
            'remark': blacklist.remark,
            'status': getattr(blacklist, 'status', '0') or '0',  # ✅ 添加status字段
            'create_by': blacklist.create_by,
            'create_time': blacklist.create_time.isoformat() if blacklist.create_time else None
        }
        
        return ResponseUtil.success(data=result)
    except Exception as e:
        logger.error(f"获取标题黑名单失败: {e}")
        return ResponseUtil.failure(msg=str(e))


@Log(title='添加标题黑名单', business_type=BusinessType.INSERT)
@titleBlacklistRouter.post("")
async def add(
    request: Request,
    blacklist_data: dict,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    添加标题黑名单
    
    Body:
    {
        "keyword": "关键字",
        "match_type": "contains/equals/regex",
        "reason": "拉黑原因",
        "remark": "备注"
    }
    """
    try:
        # ✅ 修复：从当前用户获取用户ID和部门ID
        blacklist_data['create_by'] = current_user.user.user_id
        blacklist_data['dept_id'] = current_user.user.dept_id
        
        await TitleBlacklistService.add(db, blacklist_data)
        return ResponseUtil.success(msg="添加成功")
    except ValueError as e:
        return ResponseUtil.failure(msg=str(e))
    except Exception as e:
        logger.error(f"添加标题黑名单失败: {e}")
        return ResponseUtil.failure(msg="添加失败")


@Log(title='更新标题黑名单', business_type=BusinessType.UPDATE)
@titleBlacklistRouter.put("/{blacklist_id}")
async def update(
    blacklist_id: int,
    update_data: dict,
    db: AsyncSession = Depends(get_db)
):
    """
    更新标题黑名单
    """
    try:
        await TitleBlacklistService.update(db, blacklist_id, update_data)
        return ResponseUtil.success(msg="更新成功")
    except Exception as e:
        logger.error(f"更新标题黑名单失败: {e}")
        return ResponseUtil.failure(msg="更新失败")


@Log(title='删除标题黑名单', business_type=BusinessType.DELETE)
@titleBlacklistRouter.delete("/{blacklist_id}")
async def delete(
    blacklist_id: int,
    db: AsyncSession = Depends(get_db)
):
    """
    删除标题黑名单
    """
    try:
        await TitleBlacklistService.delete(db, blacklist_id)
        return ResponseUtil.success(msg="删除成功")
    except Exception as e:
        logger.error(f"删除标题黑名单失败: {e}")
        return ResponseUtil.failure(msg="删除失败")


@Log(title='批量删除标题黑名单', business_type=BusinessType.DELETE)
@titleBlacklistRouter.delete("")
async def batch_delete(
    ids: str,
    db: AsyncSession = Depends(get_db)
):
    """
    批量删除标题黑名单
    
    Query:
        ids: 1,2,3
    """
    try:
        blacklist_ids = [int(id) for id in ids.split(',')]
        await TitleBlacklistService.batch_delete(db, blacklist_ids)
        return ResponseUtil.success(msg="删除成功")
    except Exception as e:
        logger.error(f"批量删除标题黑名单失败: {e}")
        return ResponseUtil.failure(msg="删除失败")

